const router = require('koa-router')();
const {treeTableSave} = require("../tools/treeTableSave");
const {db, Op, QueryTypes} = require("../models/db");
const tool = require("../tools/tool");
router.post('/menu/list', async ctx => {
    try {
        ctx.suc('', await tool.getMenu(ctx))
    }
    catch (error) {
        ctx.err(error)
    }
})

router.post('/menu/save', async ctx => {
    try {
        let mod = 'menu';
        let ret = await treeTableSave(mod, ctx)
        if (ret) return  ctx.suc('保存成功', ret)
        return ctx.err('保存失败')
    }
    catch (error) {
        ctx.err(error)
    }
})
router.post('/menu/saveTenant', async ctx => {
    let mod = 'tenantMenu';
    let formData = ctx.request.body.formData;
    let tenantId = ctx.request.body.tenantId;
    await db.transaction(async (t) => {
        await db.models[mod].destroy({
            where: {
                tenantId: tenantId
            }
        }, {transaction: t})
        if(formData.length > 0) {
            await db.models[mod].bulkCreate(formData, {transaction: t})
        }
    })
    return ctx.suc('权限设置成功')
})
router.post('/menu/del', async ctx => {
    try {
        let id = ctx.request.body.id;
        let code = await db.models['menu'].findOne({
            where: { id: id }
        })
        if(code.code) {
            await db.models['menu'].destroy({
                where: {
                    code: {
                        [Op.like]: code.code +'%'
                    }
                }
            })
            return ctx.suc('已删除')
        }
        return ctx.suc('无删除记录')
    }
    catch (error) {
        ctx.err(error)
    }
})
router.post('/menu/myMenu', async ctx => {
    try {
        let menu = await tool.getMenu(ctx)
        ctx.suc('', menu)
    }
    catch (error) {
        ctx.err(error)
    }
})
router.post('/menu/roleMenu', async ctx => {
    let roleId = ctx.request.body.roleId;
    let tid = ctx.user.tenantId;

    let sql = `select case when b.roleId is null then 0 else 1 end checked,a.id,a.name,a.name title,a.pid,a.isBill,a.isReport,a.sort,
       isnull(b.canAdd,0) canAdd, isnull(b.canEdit,0) canEdit,
       isnull(b.canDel,0) canDel,isnull(b.canAccount,0) canAccount,isnull(b.canWaste,0) canWaste
             from (
             select a.* from menu a inner join tenant_menu b on a.id=b.menuId and b.tenantId=${tid} and a.display=1
             ) a left join (
                select * from role_menu where roleId=${roleId}
             ) b on a.id=b.menuId where a.isDelete=0  order by a.sort`
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', ret)
})
// 保存常用菜单
router.post('/menu/saveUsedMenu', async ctx => {
    try {
        let menuId = ctx.request.body.id;
        let adminId = ctx.user.id;
        let tenantId = ctx.user.tenantId;
        let obj = {
            menuId: menuId,
            adminId: adminId,
            tenantId: tenantId,
        }
        let model = await db.models['menuUsed'].findOne({
            where: obj
        })
        if(model) {
            await model.increment({times: 1})
        }
        else {
            obj.times = 1
            await db.models['menuUsed'].create( obj )
        }
        ctx.suc('')
    } catch (e) {
        return ctx.err(e)
    }
})
router.post('/menu/setOp', async ctx => {
    let body = ctx.request.body
    let roleId = body.roleId;
    let menuId = body.menuId;
    let op = body.op;
    let checked = body.checked;
    let val = checked ? 1 : 0;
    await db.query(`update role_menu set ${op}=${val} where roleId=${roleId} and menuId=${menuId}`, {type: QueryTypes.UPDATE})
    return ctx.suc('已更新');
})
router.post('/menu/setRoleAuth', async ctx => {
    let body = ctx.request.body;
    let records = body.records;
    let roleId = body.roleId;
    let checked = body.checked;
    let ids = [];
    records.map(row => {
        ids.push(row.id)
    })
    let menuIds = ids.join(',');
    await db.transaction(async (t) => {
        await db.query(`delete from role_menu where roleId=${roleId} and menuId in(${menuIds})`, {type: QueryTypes.DELETE}, {transaction: t})
        if (checked) {
            let menuIdsql = `select id menuId from menu where id in (${menuIds}) union select id from menu where id in
                                                                                    (select pid from menu where id in (${menuIds})) `;
            let sqls = `MERGE into role_menu as a using (SELECT ${roleId} roleId, menuId from (${menuIdsql}) a ) b on a.roleId = b.roleId and a.menuId=b.menuId
                when not matched then insert (roleId, menuId, canAdd, canEdit,canDel,canAccount,canWaste) values  (b.roleId, b.menuId, 1,1,1,1,1);`
            await db.query(sqls, {type: QueryTypes.UPDATE}, {transaction: t})
        }
    })
    return ctx.suc('已更新');v
})
// 手机工作台菜单
router.post('/menu/getAppMenu', async ctx => {
    let ret = [
        {
            title: '收款相关', color: '#1e9fff', list: [
                {title: '新增收款', route: 'addSk', icon: 'fa fa-rmb'},
                {title: '交款核对', route: 'jkhd', icon: 'fa fa-check-square-o'},
                // {title: '收款记录', route: 'skJl', icon: 'fa fa-list-ol'},
                // {title: '收款统计', route: 'skTj', icon: 'fa fa-pie-chart'},
            ]
        },
        {
            title: '常用功能', color: '#F56C6C', list: [
                {title: '客户拜访', route: 'bf', icon: 'fa fa-user'},
                // {title: '我的拜访', route: 'bfMy', icon: tool.getPicUrl('appicon/我的拜访.png').url},
                {title: '拜访记录', route: 'bfMy', icon: ''},
                // {title: '全部客户', route: 'customerList', icon: tool.getPicUrl('appicon/全部客户.png').url},
                {title: '拜访轨迹', route: 'bfGj', icon: ''},
                {title: '新增客户', route: 'contactAdd', icon: ''},
                {title: '我的客户', route: 'contactMy', icon: ''},
            ]
        },
        // {
        //     title: '资料设置', color: '#1e9fff', list: [
        //         {title: '用户管理', route: 'user', icon: ''},
        //         // {title: '拜访设置', route: 'bfSets', icon: tool.getPicUrl('appicon/拜访设置.png').url},
        //         {title: '拜访线路', route: 'bfLine', icon: ''},
        //         // {title: '奖品管理', route: 'jpgl', icon: tool.getPicUrl('appicon/奖品管理.png').url},
        //         {title: '客户分类', route: 'customerCategoryList', icon: ''},
        //         {title: '部门设置', route: 'dept', icon: ''},
        //         // {title: '角色设置', route: 'role', icon: tool.getPicUrl('appicon/角色设置.png').url},
        //     ]
        // }
    ]
    return ctx.suc('', ret)
})


module.exports = router;
